/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import gridFooter from './production_extend/Production_RequisitionListGridFooter.vue'
import gridHeader from './production_extend/Production_RequisitionListGridHeader.vue'
import { chunkArray } from '@/uitils/utils'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter,
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      this.single = true
      this.columnIndex = true
      this.tableMaxHeight = (document.body.clientHeight - 260) / 2
      const { permission } = this.$store.getters.getPermission(
        '/Production_Requisition'
      )
      this.buttons.forEach((item) => {
        if (item.value == 'Audit') {
          item.onClick = () => {
            this.$refs.gridFooter.audit();
          }
        }
      })

      if (permission.includes('TransferPurchase')) {
        this.buttons.push({
          name: '转采购单',
          icon: 'el-icon-document',
          type: 'primary',
          onClick: () => {
            this.$refs.gridFooter.TransferPurchase();
          },
        })
      }

      if (permission.includes('print')) {
        this.buttons.push({
          name: '编辑并打印',
          icon: 'el-icon-printer',
          type: 'primary',
          onClick: async () => {
            try {
              let data = this.$refs.gridFooter.printData()
              console.log(data)
              if (data.length == 0)
                return this.$message.warning('请选择要打印的数据')
              let moCode = data[0].MoCode
              let ids = data.map((item) => {
                // if (item.Status == 1) {
                //   throw new Error('请选择未审核的数据')
                // }
                return item.ReqList_Id
              })

              let res = await this.http.post(
                '/api/Production_Requisition/Print',
                {
                  moCode,
                  ids,
                },
                true
              )

              const list = data.map((item, index) => {
                let element = null
                res.data.list.forEach((item2, index2) => {
                  if (index == index2) {
                    element = {
                      ...item2,
                      reqList_Id: item.ReqList_Id,
                    }
                  }
                })
                return element
              })
              // console.log(list)

              this.$refs.gridHeader.open(
                {
                  ...res.data,
                  list,
                  moCode,
                },
                this.print
              )
              // let printData = this.$refs.gridHeader.getPrintData()
              // console.log(printData);
              // this.print(res.data, moCode)
            } catch (error) {
              this.$message.error(error.message)
            }
          },
        })
      }
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      this.$nextTick(() => {
        if (result.length) this.$refs.gridFooter.rowClick(result[0])
      })
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
      this.$refs.table.$refs.table.toggleRowSelection(row) //单击行时选中当前行;
      this.$refs.gridFooter.rowClick(row)
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    },
    print(data) {
      let printData = structuredClone(data)
      // console.log(data);
      let printWindow = window.open('', '_blank')
      printWindow.document.open()
      let style = `<style>
                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                      }

                      th {
                        border: 1px solid #000;
                      }

                      .grid_table tr,.grid_table tr td{
                        border: 1px solid black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: space-between; 
                        list-style: none;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .cb {
                        margin-left: 20px;
                        text-align: left;
                      }
                    </style>`

      let table = ''
      let result = chunkArray(printData.list, 24)

      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          main += `<tr>
            <td>${index + 1}</td>
            <td>${item.invCode == null ? '' : item.invCode}</td>
            <td>${item.invName == null ? '' : item.invName}</td>
            <td>${item.invStd == null ? '' : item.invStd}</td>
            <td>${item.qty == null ? '' : item.qty}</td>
            <td>${item.realityQty == null ? '' : item.realityQty}</td>
            <td>${item.shouldQty == null ? '' : item.shouldQty}</td>
            <td>${item.unitName == null ? '' : item.unitName}</td>
            <td>${item.needDate == null ? '' : item.needDate}</td>
            <td>${item.remark == null ? '' : item.remark}</td>
          </tr>`
        })

        table += `<table class="grid_table">
          <thead>
            <tr>
              <th colspan="10">昆山鸿永峻精密五金电子科技有限公司</th>
            </tr>
            <tr>
              <th colspan="10">请购申请单</th>
            </tr>
            <tr>
              <th>请购单位</th>
              <th>${printData.department == null ? '' : data.department}</th>
              <th>订单号</th>
              <th>${printData.moCode == null ? '' : data.moCode}</th>
              <th>产品编码</th>
              <th>${printData.invCode == null ? '' : data.invCode}</th>
              <th>请购日期</th>
              <th>${printData.date == null ? '' : data.date}</th>
              <th>客户</th>
              <th>${printData.customer == null ? '' : data.customer}</th>
            </tr>
            <tr>
              <th>项次</th>
              <th>物料编码</th>
              <th>物料名称</th>
              <th>规格型号</th>
              <th>订单需求量</th>
              <th>标准需求</th>
              <th>应采购数量</th>
              <th>单位</th>
              <th>需求日</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${main}
           <tr>
            <td colspan="2">采购</td>
            <td colspan="2">总经理</td>
            <td colspan="2">副总经理</td>
            <td colspan="2">部门主管</td>
            <td>仓管</td>
            <td>申请人</td>
           </tr>
           <tr>
            <td colspan="2">&nbsp;</td>
            <td colspan="2">&nbsp;</td>
            <td colspan="2">&nbsp;</td>
            <td colspan="2">&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
           </tr>
          </tbody>
        </table>`
      })

      // let sscript = ` <script src="/qrcode.min.js" type="application/javascript"></script>
      //                 <script>
      //                   window.addEventListener("DOMContentLoaded", ()=> {
      //                     const qrcodeImgEl = document.getElementById('qrcodeImg')
      //                     qrcodeImgEl.innerHTML = ''
      //                     let qrcode = new QRCode(qrcodeImgEl, {
      //                                             width: 100,
      //                                             height: 100,
      //                                             colorDark: '#000000',
      //                                             colorLight: '#ffffff',
      //                                             correctLevel: QRCode.CorrectLevel.H,
      //                                   })
      //                     qrcode.makeCode('111')
      //                   })
      //                 </script>`
      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(table)
      printWindow.document.write(`</body></html>`)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
